﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NStateMachine<T>
{
    private T m_pOwner;

    private string m_sCurrentState;
    private string m_sPreviousState;
    private string m_sGloabState;

    public string CurrentState { get { return m_sCurrentState; } }
    public string PreviousState { get { return m_sPreviousState; } }
    public string GloabState { get { return m_sGloabState; } }


    private Dictionary<string, NState<T>> m_dicStates = new Dictionary<string, NState<T>>();

    public NStateMachine(T owner,Dictionary<string,NState<T>> states,string gloabState)
    {
        m_pOwner = owner;
        m_dicStates = states;
        m_sGloabState = gloabState;
    }

    public void OnUpdate()
    {
        if (m_dicStates.ContainsKey(m_sGloabState))
        {
            m_dicStates[m_sGloabState].Execute(m_pOwner);
        }
        if (m_dicStates.ContainsKey(m_sCurrentState))
        {
            m_dicStates[m_sCurrentState].Execute(m_pOwner);
        }
    }

    /// <summary>
    /// 切换到某个状态
    /// </summary>
    /// <param name="newState">新状态</param>
    public void ChangeState(string newState,params object[] args)
    {
        if (!m_dicStates.ContainsKey(newState))
        {
            Debug.Log("Don't have state: "+newState);
            return;
        }

        m_sPreviousState = m_sCurrentState;
        m_sCurrentState = newState;
        if (m_sPreviousState!= null && m_dicStates.ContainsKey(m_sPreviousState))
        {
            m_dicStates[m_sPreviousState].Exit(m_pOwner, args);
        }
        if (m_sCurrentState!=null && m_dicStates.ContainsKey(m_sCurrentState))
        {
            m_dicStates[m_sCurrentState].Enter(m_pOwner, args);
        }
    }

    public bool OnHandleMessage(MessageBody message)
    {
        if (m_sGloabState != null && m_dicStates.ContainsKey(m_sGloabState))
        {
            if (m_dicStates[m_sGloabState].OnMessage(m_pOwner, message))
            {
                return true;
            }
        }

        if (m_sCurrentState != null && m_dicStates.ContainsKey(m_sCurrentState))
        {
            if (m_dicStates[m_sCurrentState].OnMessage(m_pOwner, message))
            {
                return true;
            }
        }


        return false;
    }


    /// <summary>
    /// 切换到上一个状态
    /// </summary>
    public void ReturnBackState()
    {
        ChangeState(m_sPreviousState);
    }
    
    /// <summary>
    /// 是否处于某个状态
    /// </summary>
    /// <param name="state"></param>
    /// <returns></returns>
    public bool IsInState(string state)
    {
        return m_sCurrentState.Equals(state);
    }
}
